package com.teamtgv.shareshark;

import java.security.MessageDigest;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.Window;

import com.teamtgv.shareshark.R;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

public class MainActivity extends FragmentActivity {

	private static final int SPLASH = 0;
	private static final int HOME = 1;
	private static final int NOINTERNET = 2;
	private static final int SERVERUNREACHABLE = 3;
	private static final int FRAGMENT_COUNT = HOME + 3;

	private InternetChecker internetChecker = new InternetChecker(this);
	
	private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
	private boolean isResumed = false;
	private UiLifecycleHelper uiHelper;
	
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try {
		    PackageInfo info = getPackageManager().getPackageInfo(
		            "com.teamtgv.shareshark", 
		            PackageManager.GET_SIGNATURES);
		    for (Signature signature : info.signatures) {
		        MessageDigest md = MessageDigest.getInstance("SHA");
		        md.update(signature.toByteArray());
		        Log.v("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
		        }
		} catch (Exception e) {
			Log.v("KeyHash:", "Unable to determine");
		}
		
		
		// hide title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);
		
		 
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);

		FragmentManager fm = getSupportFragmentManager();
		fragments[SPLASH] = fm.findFragmentById(R.id.inlogFragment);
		fragments[HOME] = fm.findFragmentById(R.id.mainFragment);
		fragments[NOINTERNET] = fm.findFragmentById(R.id.noInternetFragment);
		fragments[SERVERUNREACHABLE] = fm.findFragmentById(R.id.serverUnreachableFragment);

		FragmentTransaction transaction = fm.beginTransaction();
		for (int i = 0; i < fragments.length; i++) {
			transaction.hide(fragments[i]);
		}
		transaction.commit();

	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (isResumed) {
			FragmentManager manager = getSupportFragmentManager();
			int backStackSize = manager.getBackStackEntryCount();
			for (int i = 0; i < backStackSize; i++) {
				manager.popBackStack();
			}
			// check for the OPENED state instead of session.isOpened() since
			// for the
			// OPENED_TOKEN_UPDATED state, the selection fragment should already
			// be showing.
			if (! internetChecker.isOnline()) {
				showFragment(NOINTERNET, false);
			} else if (! internetChecker.serverReachable()) {
				showFragment(SERVERUNREACHABLE, false);
			} else if (state.equals(SessionState.OPENED)) {
				showFragment(HOME, false);
			} else if (state.isClosed()) {
				UserData.clear();
				showFragment(SPLASH, false);
			}
		}
	}

	@Override
	protected void onResumeFragments() {
		super.onResumeFragments();
		Session session = Session.getActiveSession();
		
		if (! internetChecker.isOnline()) {
			showFragment(NOINTERNET, false);
			Log.v("MainActivity", "Starting no internet fragment");
		} else if (! internetChecker.serverReachable()) {
			showFragment(SERVERUNREACHABLE, false);
			Log.v("MainActivity", "Starting server unreachable fragment");
		} else if (session != null && session.isOpened()) {
			// if the session is already open, try to show the selection
			// fragment
			Log.v("MainActivity", "Starting main fragment");
			showFragment(HOME, false);
		} else {
			// otherwise present the splash screen and ask the user to login.
			showFragment(SPLASH, false);
			Log.v("MainActivity", "Starting fb fragment");
		}
	}

	private void showFragment(int fragmentIndex, boolean addToBackStack) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		for (int i = 0; i < fragments.length; i++) {
			if (i == fragmentIndex) {
				transaction.show(fragments[i]);
			} else {
				transaction.hide(fragments[i]);
			}
		}
		if (addToBackStack) {
			transaction.addToBackStack(null);
		}
		transaction.commit();
	}

	@Override
	public void onResume() {
		super.onResume();
		uiHelper.onResume();
		isResumed = true;
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
		isResumed = false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return false;
	}

}
